package com.bkgy.modular.excellentqualitysample.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSONObject;
import com.bkgy.excelhandle.PlanExcelHandlerImpl;
import com.bkgy.modular.excellentqualitysample.dao.ThickExcellentQualitySampleDao;
import com.bkgy.modular.excellentqualitysample.entity.ExportThickExcellentQualitySample;
import com.bkgy.modular.excellentqualitysample.entity.ThickExcellentQualitySample;
import com.bkgy.modular.tbdecsionrule.entity.TbDecsionRule;
import com.bkgy.modular.tbdecsionrule.service.impl.TbDecsionRuleServiceImpl;
import com.bkgy.sys.common.entity.ResultData;
import com.bkgy.util.CalUtils;
import com.bkgy.util.ExcelUtilsPOI;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ThickExcellentQualitySampleService {

    @Resource
    private ThickExcellentQualitySampleDao thickExcellentQualitySampleDao;
    @Resource
    private TbDecsionRuleServiceImpl tbDecsionRuleService;
    @Resource
    private CalUtils calUtils;

    public ResultData findDataByPage(JSONObject json) {
        try {
            Integer pageIndex = json.getInteger("pageIndex");
            Integer pageSize = json.getInteger("pageSize");
            if (pageIndex == null || pageSize == null) {
                return ResultData.ResultDataFaultSelf("分页参数没有传", null);
            }
            //查询条件
            String cold_coil_id = null;
            String hot_id = null; // 热卷号
            String dbegin = null;
            String dend = null;
            String thick_trg_interval = null;  //产品厚度
            String width_trg_interval = null;  //原料宽度
            String ele_si1 = null;  //硅含量---开始
            String ele_si2 = null;  //硅含量---结束
            String steelgrade = null;  //钢种
            String shift = null;
            String crew = null;
            JSONObject condition = json.getJSONObject("condition");
            if (!condition.isEmpty()) {
                if (StringUtils.hasText(condition.getString("cold_coil_id"))) {
                    cold_coil_id = condition.getString("cold_coil_id");
                }
                if (StringUtils.hasText(condition.getString("hot_id"))) {
                    hot_id = condition.getString("hot_id");
                }
                if (StringUtils.hasText(condition.getString("dbegin"))) {
                    dbegin = condition.getString("dbegin");
                    dbegin = calUtils.calDateTime(dbegin);
                }
                if (StringUtils.hasText(condition.getString("dend"))) {
                    dend = condition.getString("dend");
                    dend = calUtils.calDateTime(dend);
                }
                if (StringUtils.hasText(condition.getString("thick_trg_interval"))) {
                    thick_trg_interval = condition.getString("thick_trg_interval");
                }
                if (StringUtils.hasText(condition.getString("width_trg_interval"))) {
                    width_trg_interval = condition.getString("width_trg_interval");
                }
                if (StringUtils.hasText(condition.getString("ele_si1"))) {
                    ele_si1 = condition.getString("ele_si1");
                }
                if (StringUtils.hasText(condition.getString("ele_si2"))) {
                    ele_si2 = condition.getString("ele_si2");
                }
                if (StringUtils.hasText(condition.getString("steelgrade"))) {
                    steelgrade = condition.getString("steelgrade");
                }
                if (StringUtils.hasText(condition.getString("shift"))) {
                    shift = condition.getString("shift");
                }
                if (StringUtils.hasText(condition.getString("crew"))) {
                    crew = condition.getString("crew");
                }
            }
            String halfYear = LocalDate.now().minusMonths(6L).toString();
            List<ThickExcellentQualitySample> list = thickExcellentQualitySampleDao.findDataByPage(dbegin, dend, thick_trg_interval, width_trg_interval,ele_si1, ele_si2, steelgrade, shift, crew, cold_coil_id,halfYear,hot_id);
//            Integer count = thickExcellentQualitySampleDao.findDataCount(dbegin, dend, ex_thk1, ex_thk2, en_wid1, en_wid2, en_thk1, en_thk2, ele_si1, ele_si2, steelgrade, shift, crew, cold_coil_id);
            List<TbDecsionRule> rules = tbDecsionRuleService.list();
            List<ThickExcellentQualitySample> list1 = null;
            if(pageIndex * pageSize>list.size()){
                list1 = list.subList((pageIndex - 1) * pageSize, list.size());
            }else {
                list1 = list.subList((pageIndex - 1) * pageSize, pageIndex * pageSize);
            }

            for (ThickExcellentQualitySample sample : list1) {
                Double thickCode = sample.getThick_trg_interval();
                Double widthCode = sample.getWidth_trg_interval();
                TbDecsionRule rule1 = findstands(rules, thickCode.toString());
                TbDecsionRule rule2 = findstands(rules, (thickCode-1)+"");
                TbDecsionRule rule3 = findstands(rules, widthCode.toString());
                TbDecsionRule rule4 = findstands(rules, (widthCode-1)+"");
                if(thickCode!=1.0){
                    sample.setThickInterval(thickCode+":"+rule2.getProduct_thk()+"-"+rule1.getProduct_thk());
                }else {
                    sample.setThickInterval(thickCode+":0-"+rule1.getProduct_thk());
                }
                if(widthCode!=1.0){
                    sample.setWidthInterval(widthCode+":"+rule4.getProduct_wid()+"-"+rule3.getProduct_wid());
                }else {
                    sample.setWidthInterval(widthCode+":0-"+rule3.getProduct_wid());
                }
            }
            return ResultData.ResultDataSuccess(list1,list.size());

        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("查询失败,失败信息为" + e.getMessage(), null);
        }
    }

    //根据order查找指定标准
    private TbDecsionRule findstands(List<TbDecsionRule> list, String order) {
        List<TbDecsionRule> tblist = list.stream().filter(x ->order.equals(x.getOrder().toString())).collect(Collectors.toList());

        TbDecsionRule tbDecsionRule = new TbDecsionRule();
        if (tblist.size() != 0) {
            tbDecsionRule = tblist.get(0);
        }
        return tbDecsionRule;
    }

    public void export(JSONObject jsonObject, HttpServletResponse response) {
        // 接收传入参数
        Integer pageSize = jsonObject.getInteger("pageSize");
        Integer pageCount = jsonObject.getInteger("pageCount");
        String fileNames = jsonObject.getString("fileName");
        JSONObject condition = jsonObject.getJSONObject("condition");
        //查询条件
        String cold_coil_id = null;
        String hot_id = null; // 热卷号
        String dbegin = null;
        String dend = null;
        String thick_trg_interval = null;  //产品厚度
        String width_trg_interval = null;  //原料宽度
        String ele_si1 = null;  //硅含量---开始
        String ele_si2 = null;  //硅含量---结束
        String steelgrade = null;  //钢种
        String shift = null;
        String crew = null;
        if (!condition.isEmpty()) {
            if (StringUtils.hasText(condition.getString("cold_coil_id"))) {
                cold_coil_id = condition.getString("cold_coil_id");
            }
            if (StringUtils.hasText(condition.getString("hot_id"))) {
                hot_id = condition.getString("hot_id");
            }
            if (StringUtils.hasText(condition.getString("dbegin"))) {
                dbegin = condition.getString("dbegin");
                dbegin = calUtils.calDateTime(dbegin);
            }
            if (StringUtils.hasText(condition.getString("dend"))) {
                dend = condition.getString("dend");
                dend = calUtils.calDateTime(dend);
            }
            if (StringUtils.hasText(condition.getString("thick_trg_interval"))) {
                thick_trg_interval = condition.getString("thick_trg_interval");
            }
            if (StringUtils.hasText(condition.getString("width_trg_interval"))) {
                width_trg_interval = condition.getString("width_trg_interval");
            }
            if (StringUtils.hasText(condition.getString("ele_si1"))) {
                ele_si1 = condition.getString("ele_si1");
            }
            if (StringUtils.hasText(condition.getString("ele_si2"))) {
                ele_si2 = condition.getString("ele_si2");
            }
            if (StringUtils.hasText(condition.getString("steelgrade"))) {
                steelgrade = condition.getString("steelgrade");
            }
            if (StringUtils.hasText(condition.getString("shift"))) {
                shift = condition.getString("shift");
            }
            if (StringUtils.hasText(condition.getString("crew"))) {
                crew = condition.getString("crew");
            }
        }
        String halfYear = LocalDate.now().minusMonths(6L).toString();
        List<ThickExcellentQualitySample> list = thickExcellentQualitySampleDao.findDataByPage(dbegin, dend, thick_trg_interval, width_trg_interval,ele_si1, ele_si2, steelgrade, shift, crew, cold_coil_id,halfYear,hot_id);


        // 创建表格数据集合
        List<ThickExcellentQualitySample> listExcel = new ArrayList<>();
        for (int i = 1; i <= pageCount; i++) {
            List<TbDecsionRule> rules = tbDecsionRuleService.list();
            List<ThickExcellentQualitySample> list1 = null;
            if(i * pageSize > list.size()){
                list1 = list.subList((i - 1) * pageSize, list.size());
            }else {
                list1 = list.subList((i - 1) * pageSize, i * pageSize);
            }
            for (ThickExcellentQualitySample sample : list1) {
                Double thickCode = sample.getThick_trg_interval();
                Double widthCode = sample.getWidth_trg_interval();
                TbDecsionRule rule1 = findstands(rules, thickCode.toString());
                TbDecsionRule rule2 = findstands(rules, (thickCode-1)+"");
                TbDecsionRule rule3 = findstands(rules, widthCode.toString());
                TbDecsionRule rule4 = findstands(rules, (widthCode-1)+"");
                if(thickCode!=1.0){
                    sample.setThickInterval(thickCode+":"+rule2.getProduct_thk()+"-"+rule1.getProduct_thk());
                }else {
                    sample.setThickInterval(thickCode+":0-"+rule1.getProduct_thk());
                }
                if(widthCode!=1.0){
                    sample.setWidthInterval(widthCode+":"+rule4.getProduct_wid()+"-"+rule3.getProduct_wid());
                }else {
                    sample.setWidthInterval(widthCode+":0-"+rule3.getProduct_wid());
                }

                listExcel.add(sample);
            }
        }
        List<ExportThickExcellentQualitySample> listThickExcellentQualitySample = new ArrayList<>();
        if (!listExcel.isEmpty() && listExcel.size() > 0) {
            for (ThickExcellentQualitySample item : listExcel) {
                ExportThickExcellentQualitySample exportThickExcellentQualitySample = new ExportThickExcellentQualitySample();
                BeanUtils.copyProperties(item,exportThickExcellentQualitySample);
                listThickExcellentQualitySample.add(exportThickExcellentQualitySample);
            }
        }
        try {
            Map<String,Object> data1 = new HashMap();
            data1.put("data",listThickExcellentQualitySample);
            File file = ResourceUtils.getFile("classpath:exceltemplate\\厚度优秀样本.xlsx");
            TemplateExportParams templateExportParams = new TemplateExportParams(file.getPath(),false);
            templateExportParams.setDictHandler(new PlanExcelHandlerImpl());
            Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, data1);
            ExcelUtilsPOI.exportExcel(fileNames,response,workbook);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }



    }
}